<?php
class Nvl_Model extends CI_Model{
	public $table_name='';
	public $column_primary='';
	public $column_order='';
	public $column_unique='';
	public $primary_filter='intval';
	
	function __coreList($sql, $array=FALSE){
		$query = $this->db->query($sql);
		$res = array();
		$res['Result'] = "OK";
		$res['TotalRecordCount'] = $this->__countRows($sql);
		$res['Records'] = $query->result();
		return ($array == FALSE) ? json_encode($res) : $res;
	}
	
	/*
	 * Function For Count Query Record Result
	*/
	function __countRows($sql){
		$sqli="";
		$sqls="";
		$split_order=preg_split("/ORDER/i",$sql);
		$sqls=$split_order[0];
		$split_order=preg_split("/LIMIT/i",$sql);
		$sqls=$split_order[0];
		$split_sql=preg_split("/FROM/i",$sqls);
		$sqli.="SELECT count(1) as jumlah ";
		for($i=1;$i<sizeof($split_sql);$i++){
			$sqli.=' FROM '.$split_sql[$i];
		}
		$rs=$this->db->query($sqli);
		if($rs->num_rows()){
			$row=$rs->row();
			return $row->jumlah;
		}else{
			return 0;
		}
	}
	
	/*
	 * Function to check is column value is unique or not
	*/
	public function __checkCodeExisting($dataValue, $primaryValue){
		if($this->column_unique != ''){
			$this->db->where($this->column_unique, $dataValue[$this->column_unique]);
			$this->db->where($this->column_primary . ' != ', $primaryValue);
			$res = $this->db->get($this->table_name);
			if($res->num_rows() > 0){
				return true;
			}
		}else{
			return true;
		}
		return false;
	}
	
	/*
	 * Function to save data
	 * - data (array)
	 * - id (int)
	 * - table (string)
	 * - return_id (boolean)
	 * - col_prom (string)
	*/
	public function __save($data, $id=0, $table=FALSE, $return_id=FALSE, $col_prim=FALSE){
		$table = ($table != FALSE) ? $table : $this->table_name ;
		$result = '{"Result":"Fail"}';
		if($this->__checkCodeExisting($data, $id)){
			if($id==0){
				$this->db->set($data)->insert($table);
				if($this->db->affected_rows()){
					$result = ($return_id == TRUE) ? $this->db->insert_id() : '{"Result":"OK"}';
				}
			}else{
				$col_prim = ($col_prim!=FALSE) ? $col_prim : $this->column_primary ;
				$filter = $this->primary_filter;
				$this->db->set($data)->where($col_prim, $filter($id))->update($table);
				if($this->db->affected_rows()){
					$result = ($return_id == TRUE) ? $id : '{"Result":"OK"}';
				}
			}
		}else{
			$result = '{"Result":"Duplicate"}';
		}
		return $result;
	}
	
	public function __delete($ids, $table=FALSE){
		$table = ($table!=FALSE) ? $table : $this->table_name ;
		$filter = $this->primary_filter;
        $ids = ! is_array($ids) ? array($ids) : $ids;
        foreach ($ids as $id) {
            $id = $filter($id);
            if ($id) {
                $this->db->where($this->column_primary, $id)->limit(1)->delete($table);
            }
        }
		if($this->db->affected_rows()){
			return '{"Result":"OK"}';
		}else{
			return '{"Result":"Fail"}';
		}
	}
	
}